package com.example.SearchZB;

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/11/26.
 */
public class CategoryManager {

    public List<Map<String, Object>> getCategoryData(int n) throws IOException, JSONException{

        String json = getData(n);

        JSONObject jsonObject = new JSONObject(json);

        JSONArray jsonArrayresult = jsonObject.optJSONArray("result");

        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();

        for (int i = 0;i<jsonArrayresult.length();i++){

            Map<String,Object> map = new HashMap<String, Object>();

            JSONObject objectresult = jsonArrayresult.getJSONObject(i);

            String id = objectresult.optString("id");
            String name = objectresult.optString("name");
            map.put("id",id);
            map.put("name",name);
            list.add(map);
        }
        return list;
    }



    public List<Map<String, Object>> getLv1CategoryData(int n) {
        return null;
    }

    public List<Map<String, Object>> getLv2CategoryData() {
        return null;
    }


    public String getData(int n) throws IOException {

        String path = "http://apis.juhe.cn/baidu/getCategory?";
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();

        pairs.add(new BasicNameValuePair("key","fa5373926e0223b0ea311f95cfe21597"));
        pairs.add(new BasicNameValuePair("fid",n+""));
        Log.d("pairs", pairs.toString());

        String paramStr = URLEncodedUtils.format(pairs, "utf-8");
        Log.d("paramStr",paramStr);
        HttpGet httpget = new HttpGet(path+paramStr);

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse httpResponse = httpClient.execute(httpget);

        HttpEntity httpEntity = httpResponse.getEntity();

        InputStream inputStream = httpEntity.getContent();

        ByteArrayOutputStream byOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buffer))!=-1){
            byOutputStream.write(buffer,0,len);
        }
        String result = byOutputStream.toString();

        Log.d("",result);

        return result;
    }

}
